/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.openmrs.module.basicmodule.DSS.Interpreter.Function.List;

import org.openmrs.module.basicmodule.DSS.Interpreter.Function.Function;
import java.util.ArrayList;
import org.openmrs.module.basicmodule.DSS.Interpreter.DSSObservation;
import org.openmrs.module.basicmodule.DSS.Interpreter.InterpreterVisitor;
import org.openmrs.module.basicmodule.DSS.ast.AST;

/**
 *
 * @author Stephen
 */
public class SortDataFunction extends Function {
    
    @Override
    public Object execute(ArrayList args) {
        ArrayList list1 = (ArrayList) ((AST)args.get(0)).accept(new InterpreterVisitor());
        
        boolean swapped = true;
        while (swapped) {
            swapped = false;
            for (int i = 0; i < list1.size() - 1; i ++) {
                DSSObservation obj1 = (DSSObservation) list1.get(i);
                DSSObservation obj2 = (DSSObservation) list1.get(i+1);
                if (compare(obj2, obj1)) {
                    list1.remove(i+1);
                    list1.add(i, obj2);
                    swapped = true;
                }
            }
        }
        
//        for (int i = 0; i < list1.size(); i++) {
//            System.out.println(((DSSObservation)list1.get(i)).getValue().toString());
//        }
        return list1;
    }
    
    /**
     * Compares 2 Observations
     * @param o1 is the first object
     * @param o2 is the second object
     * @return is true if o1 is less than o2 else returns false
     */
    private boolean compare(DSSObservation o1, DSSObservation o2) {
        String type = o1.getType();
        if (type.equalsIgnoreCase("int")) {
            int val1 = (Integer)o1.getValue();
            int val2 = (Integer)o2.getValue();
            return (val1 < val2);
        } else if (type.equalsIgnoreCase("float")) {
            Float val1 = (Float)o1.getValue();
            Float val2 = (Float)o2.getValue();
            return (val1 < val2);
        } else if (type.equalsIgnoreCase("string")) {
            String val1 = (String)o1.getValue();
            String val2 = (String)o2.getValue();
            int ret = val1.compareTo(val2);
            if (ret < 0) {
                return true;
            } else {
                return false;
            }
        }
        throw new UnsupportedOperationException("Not supported yet.");
    }
}
